<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace User\Validator;

use Admin\Data\Common;
use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;
use User\Entity\User;
use User\Entity\UserNameLog;
use function JmesPath\search;

class UserNameValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const USER_EXISTS   = 'userExists';
    const USER_NOT_REG  = 'userNotReg';
    const USER_EDIT_NUM = 'userEditNum';

    protected $options = [
        'entityManager',
        'userInfo'
    ];

    protected $messageTemplates = [];

    public function __construct($options = null)
    {
        if(is_array($options)) {
            if(isset($options['entityManager']))    $this->options['entityManager'] = $options['entityManager'];
            if(isset($options['userInfo']))         $this->options['userInfo']      = $options['userInfo'];
        }

        $trans = new Translator();
        $this->messageTemplates = [
            self::NOT_SCALAR    => $trans->translate("这不是一个标准输入值"),
            self::USER_EXISTS   => $trans->translate("该账户已经存在"),
            self::USER_NOT_REG  => $trans->translate("该名称内包含系统保留名称，不能修改"),
            self::USER_EDIT_NUM => $trans->translate("已超过系统允许的最大修改次数")
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        if ($value == $this->options['userInfo']->getUserName()) {
            return true;
        }

        $entityManager = $this->options['entityManager'];
        $editNameLogNum= $entityManager->getRepository(UserNameLog::class)->count(['userId' => $this->options['userInfo']->getUserId()]);
        if ($editNameLogNum >= Common::configValue('account_edit_num', 'customer')) {
            $this->error(self::USER_EDIT_NUM);
            return false;
        }

        $regRetain = Common::configValue('user_register_retain', 'customer');
        if(!empty($regRetain)) {
            $regRetainArray = explode('|', $regRetain);
            foreach ($regRetainArray as $regValue) {
                if (stripos($value, $regValue) !== false) {
                    $this->error(self::USER_NOT_REG);
                    return false;
                }
            }
        }

        $user = $entityManager->getRepository(User::class)->findCheckUserName($value, $this->options['userInfo']->getUserId());

        if($this->options['userInfo'] == null) {
            $isValid = ($user==null);
        } else {
            if($this->options['userInfo']->getUserName() != $value && $user != null)
                $isValid = false;
            else
                $isValid = true;
        }

        if(!$isValid) $this->error(self::USER_EXISTS);

        return $isValid;
    }
}